package com.riccardocardin.structured.concurrency.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

import static com.riccardocardin.structured.concurrency.model.Model.*;

public class RepositoryCache {

    private static final Logger LOGGER = LoggerFactory.getLogger("GitHubApp");

    private final Map<UserId, List<Repository>> cache = new HashMap<>();

    public RepositoryCache() {
        cache.put(
                new UserId(42L),
                List.of(
                        new Repository(
                                "rockthejvm.github.io",
                                Visibility.PUBLIC,
                                URI.create("https://github.com/rockthejvm/rockthejvm.github.io"))));
    }

    public List<Repository> findRepositories(UserId userId) throws InterruptedException {
        // Simulates access to a distributed cache (Redis?)
        delay(Duration.ofMillis(100L));
        final List<Repository> repositories = cache.get(userId);
        if (repositories == null) {
            LOGGER.info("No cached repositories found for user with id '{}'", userId);
            throw new NoSuchElementException(
                    "No cached repositories found for user with id '%s'".formatted(userId));
        }
        LOGGER.info("Found {} cached repositories for user with id '{}'", repositories.size(), userId);
        return repositories;

    }

    public void addToCache(UserId userId, List<Repository> repositories)
            throws InterruptedException {
        // Simulates access to a distributed cache (Redis?)
        delay(Duration.ofMillis(100L));
        cache.put(userId, repositories);
    }

    void delay(Duration duration) throws InterruptedException {
        Thread.sleep(duration);
    }
}
